package com.tuling.learnjuc.atomic;

import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author: Fox
 * @Desc:  CAS等价代码
 **/
public class CASDemo {

    // 内存中当前的值
    private volatile int ramAddress;

    /**
     * @param expectedValue 期望值
     * @return newValue 更新的值
     **/
    public synchronized int compareAndSwap(int expectedValue, int newValue) {
        //TODO 模拟直接从内存地址读取到内存中的值
        int oldRamAddress  = accessMemory(ramAddress);
        //内存中的值和期望的值进行比较
        if (oldRamAddress  == expectedValue) {
            ramAddress = newValue;
        }
        return oldRamAddress;
    }

    private int accessMemory(int ramAddress) {
        //TODO  模拟直接从内存地址读取到内存中的值
        return ramAddress;
    }


    public static void main(String[] args) {

        AtomicInteger atomicInteger = new AtomicInteger(5);
        System.out.println(atomicInteger.compareAndSet(5,50));
        System.out.println(atomicInteger.compareAndSet(5,100));

    }


}
